package com.liukai.bishe.ui.activity.userInfo;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.liukai.bishe.R;
import com.liukai.bishe.model.doman.user.User;
import com.liukai.bishe.model.doman.user.UserMessage;
import com.liukai.bishe.presenter.userPresenter.IUpdateHeadImgPresenter;
import com.liukai.bishe.presenter.userPresenter.IUpdateUserInfoPresenter;
import com.liukai.bishe.presenter.userPresenter.IUploadToOSSPresenter;
import com.liukai.bishe.presenter.userPresenter.impl.IUpdateHeadImgPresenterImpl;
import com.liukai.bishe.presenter.userPresenter.impl.IUpdateUserInfoPresenterImpl;
import com.liukai.bishe.presenter.userPresenter.impl.IUploadToOSSPrensterImpl;
import com.liukai.bishe.ui.adapter.UserInfoAdapter;
import com.liukai.bishe.ui.decoration.UserInfoDecoration;
import com.liukai.bishe.utils.Constants;
import com.liukai.bishe.utils.ToastUtil;
import com.liukai.bishe.view.IUpdateUserInfoCallBack;

import java.io.File;
import java.util.List;

public class UserInfoActivity extends AppCompatActivity implements IUpdateUserInfoCallBack {

    private Context mContext = UserInfoActivity.this;
    private Unbinder mBind;

    @BindView(R.id.btnBack)
    public ImageView btnBack;

    @BindView(R.id.recyclerView)
    public RecyclerView mRecyclerView;

    @BindView(R.id.userHeadImg)
    public CircleImageView mUserHeadImg;

    private UserInfoAdapter mUserInfoAdapter;
    private IUpdateHeadImgPresenter mIUpdateHeadImgPresenter; // 选择头像的Presenter

    private File mCropImageFile;
    private IUploadToOSSPresenter mIUploadToOSSPresenter; // 上传图片到阿里云的Presenter
    private IUpdateUserInfoPresenter mIUpdateUserInfoPresenter; // 修改用户信息的Presenter
    private User mUserInfo;
    private List<String> mUserInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        mBind = ButterKnife.bind(this);
        initData();
        initAdapter();
        initListener();

    }

    private void initListener() {
        // 返回按钮
        btnBack.setOnClickListener(view -> {
            setResult(RESULT_OK);
            finish();
        });

        // 头像
        mUserHeadImg.setOnClickListener(view -> {
            setupDialog();// 打开选择框
        });
    }

    private void initData() {

        mUserInfo = Constants.getUserInfo(); // 获取用户信息
        ToastUtil.log(mContext,mUserInfo.toString());
        if(mUserInfo.getUserhead()!=null && !mUserInfo.getUserhead().equals("")){
            Glide.with(this).load(mUserInfo.getUserhead()).into(mUserHeadImg);
        }else{
            Glide.with(this).load(R.mipmap.img1).into(mUserHeadImg);
        }
        Constants.setUserInfoList();
        Constants.setUserInfoMap(mUserInfo);

        mIUploadToOSSPresenter = new IUploadToOSSPrensterImpl(mContext);// 上传图片到OSS
        mIUpdateUserInfoPresenter = new IUpdateUserInfoPresenterImpl(); // 修改用户信息
        mIUpdateUserInfoPresenter.registerCallback(this);
        mIUpdateHeadImgPresenter = new IUpdateHeadImgPresenterImpl(UserInfoActivity.this); // 更新用户头像

    }

    private void initAdapter() {
        mUserInfoList = Constants.getUserInfoList();
        // 传递上下文，列表，更新用户信息的Presenter
        mUserInfoAdapter = new UserInfoAdapter(mContext,mUserInfoList,
                UserInfoActivity.this,mIUpdateUserInfoPresenter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.addItemDecoration(new UserInfoDecoration());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mUserInfoAdapter);

    }

    /**
     * 拍照，相册选择框
     */
    private void setupDialog(){

        final String[] items = {"拍照", "相册"};
        AlertDialog.Builder listDialog = new AlertDialog.Builder(UserInfoActivity.this);
        listDialog.setItems(items, (dialogInterface, i) -> {
            if (i == 0){
                mIUpdateHeadImgPresenter.camera();
            }else if (i == 1){
                mIUpdateHeadImgPresenter.gallery();
            }
        });
        listDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.REQUEST_CAMERA: // 拍照
                if (resultCode == RESULT_OK) {
                    crop(mIUpdateHeadImgPresenter.getTmpFile().getAbsolutePath());
                } else {
                    ToastUtil.log(this, "拍照失败");
                }
                break;

            case Constants.REQUEST_CROP: // 剪裁
                if (resultCode == RESULT_OK) {

                    String uploaduel = mIUploadToOSSPresenter.uploadPortrait(mCropImageFile.getAbsolutePath());// “/storage/emulated/0/XRichText/1534936652406-”是我手机里一张图片的路径
                    mUserInfo.setUserhead(uploaduel); // 修改User中的头像路径
                    mIUpdateUserInfoPresenter.update(mUserInfo); // 调用修改用户信息的方法
                    Glide.with(this).load(uploaduel).into(mUserHeadImg);
                    //这个方法会返回OSS上图片的路径
                    ToastUtil.log(mContext,"xxxx----testurl:" +uploaduel);
                    ToastUtil.log(this, mCropImageFile.getAbsolutePath());
                } else {
                    ToastUtil.log(this,"截图失败");
                }
                break;

            case Constants.REQUEST_GALLERY: // 相册
                if (resultCode == RESULT_OK && data != null) {
                    String imagePath = mIUpdateHeadImgPresenter.handleImage(data);
                    crop(mIUpdateHeadImgPresenter.handleImage(data));
                } else {
                    ToastUtil.log(this,"打开图库失败");
                }
                break;

            case Constants.REQUEST_ChANGE_NICKNAME_SUCCESS:
                if (resultCode == RESULT_OK && data != null) {
                    // 获取服务器返回的信息
                    UserMessage userMessage = (UserMessage)data.getSerializableExtra("userMessage");
                    // 刷新信息
                    update(userMessage);
                }
                break;

            case Constants.REQUEST_ChANGE_DESCRIBE_SUCCESS :
                if (resultCode == RESULT_OK && data != null) {
                    // 获取服务器返回的信息
                    UserMessage userMessage = (UserMessage)data.getSerializableExtra("userMessage");
                    // 刷新信息
                    update(userMessage);
                }
                break;

            case Constants.REQUEST_ChANGE_PASSWORD_SUCCESS :
                if (resultCode == RESULT_OK && data != null) {
                    // 获取服务器返回的信息
                    UserMessage userMessage = (UserMessage)data.getSerializableExtra("userMessage");
                    // 刷新信息
                    update(userMessage);
                }
                break;

        }
    }

    /**
     * 剪裁图片
     * @param imagePath
     */
    public void crop(String imagePath) {
        //mCropImageFile = FileUtils.createTmpFile(getBaseContext());
        mCropImageFile = mIUpdateHeadImgPresenter.getmCropImageFile();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(mIUpdateHeadImgPresenter.getImageContentUri(new File(imagePath)), "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCropImageFile));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, Constants.REQUEST_CROP);
    }


    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBind != null) {
            mBind = null;
        }
        mIUpdateUserInfoPresenter.unregisterCallback(this);
    }

    /**
     * 修改用户信息后返回的结果
     * @param object
     */
    @Override
    public void result(Object object) {
        UserMessage userMessage = (UserMessage)object; // 获取服务器的返回信息
        if (userMessage.getCode().equals("3001")){ // 修改成功
//            mUserInfo = userMessage.getUser(); // 获取修改后的信息
//            Constants.setUser(mUserInfo); //修改全局User
            update(userMessage);
//            Constants.setUserInfoList(); // 清空用户信息列表
//            Constants.setUserInfoMap(mUserInfo); //设置用户信息列表
//            mUserInfoList = Constants.getUserInfoList(); // 获取用户信息列表
//            mUserInfoAdapter.notifyDataSetChanged(); // 刷新用户信息列表
        }

    }

    private void update(UserMessage userMessage){
        mUserInfo = userMessage.getUser(); // 获取修改后的信息
        Constants.setUser(mUserInfo); //修改全局User
        ToastUtil.log(mContext,"刷新=====================》"+Constants.getUserInfo().toString());
        Constants.setUserInfoList(); // 清空用户信息列表
        Constants.setUserInfoMap(mUserInfo); //设置用户信息列表
        mUserInfoList = Constants.getUserInfoList(); // 获取用户信息列表
        mUserInfoAdapter.notifyDataSetChanged(); // 刷新用户信息列表
    }

}
